package com.sinodata.bsm.cicp.collector.weblogic9;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import javax.management.MBeanServerConnection;
import javax.management.ObjectName;
import javax.management.Query;
import javax.management.QueryExp;
import javax.management.remote.JMXConnector;

import org.apache.log4j.Logger;

import com.sinodata.bsm.cicp.collector.Collector;
import com.sinodata.bsm.cicp.exception.CollectorException;
import com.sinodata.bsm.cicp.util.JmxUtil;
import com.sinodata.bsm.common.vo.ResPropertyValue;

/**
 * 
 * <p>
 * Description: 
 * </p>
 *
 * @author liulibo
 * @version 1.0

 * <p>
 * History: 
 *
 * Date                     Author         Version     Description
 * ---------------------------------------------------------------------------------
 * 2012-12-26 AM 10:07:17   liulibo        1.0         To create
 * </p>
 *
 * @since 
 * @see
 */
public class WorkManagerCollector extends Collector {

    private static final Logger logger = Logger.getLogger(WorkManagerCollector.class);

    private final HashMap perComRequest = new HashMap();
    private final Set set = new HashSet();
    private long lastTime = -1;

    @Override
    public List<ResPropertyValue> collect(String ip) throws CollectorException {
        List<ResPropertyValue> values = new ArrayList<ResPropertyValue>();
        String serversName = this.getParamMap().get("ServerName").trim();
        String applicationName1 = this.getParamMap().get("AppName").trim();
        String managerName = this.getParamMap().get("ManagerName").trim();
        String port = this.getParamMap().get("port").trim();

        String[] propMetas = getPropMeta();
        ResPropertyValue propertyValueX = new ResPropertyValue();
        ResPropertyValue.PropValue[] propValues = new ResPropertyValue.PropValue[propMetas.length];

        String key = serversName + ":" + ip;
        String[] result = new String[3];
        ObjectName service;
        String name = null;
        Object attrValues[] = null;
        long time = System.currentTimeMillis();
        JMXConnector connector = null;
        MBeanServerConnection connection = null;
        try {
            connector = JmxUtil.getConnection(ip, Integer.parseInt(port));
            connection = connector.getMBeanServerConnection();
            service = new ObjectName("com.bea:Name=DomainRuntimeService,Type=weblogic.management.mbeanservers.domainruntime.DomainRuntimeServiceMBean");
            Object domainConfiguration = connection.getAttribute(service, "DomainConfiguration");
            ObjectName[] appDeployments = (ObjectName[]) connection.getAttribute((ObjectName) domainConfiguration, "AppDeployments");
            QueryExp typefilter = Query.match(Query.attr("Type"), Query.value("ApplicationRuntime"));
            QueryExp appfilter = null;
            if ((appDeployments != null) && (appDeployments.length > 0)) {
                for (ObjectName objectName : appDeployments) {
                    name = objectName.getKeyProperty("Name");
                    QueryExp tfilter = Query.match(Query.attr("ApplicationName"), Query.value(name));
                    if (appfilter == null) {
                        appfilter = tfilter;
                    } else {
                        appfilter = Query.or(appfilter, tfilter);
                    }
                }
                QueryExp destfilter = Query.and(typefilter, appfilter);
                long currentTimeMillis = System.currentTimeMillis();
                if (set.isEmpty() || currentTimeMillis > lastTime + 60 * 60 * 1000) {
                    set.clear();
                    Set test = connection.queryNames(new ObjectName("com.bea:*"), destfilter);
                    set.addAll(test);
                    lastTime = currentTimeMillis;
                }
                Iterator it = set.iterator();
                while (it.hasNext()) {
                    ObjectName objName = (ObjectName) it.next();
                    String applicationName = objName.getKeyProperty("Name");
                    String serverRuntime = objName.getKeyProperty("ServerRuntime");
                    if ((serverRuntime.equals(serversName)) && (applicationName1.equals(applicationName))) {
                        String attributeNames[] = new String[] { "Name", "PendingRequests", "CompletedRequests" };
                        ObjectName[] workManagerRuntimes = (ObjectName[]) connection.getAttribute(objName, "WorkManagerRuntimes");
                        for (ObjectName objectName2 : workManagerRuntimes) {
                            attrValues = JmxUtil.getAttribute(connection, objectName2, attributeNames);
                            if (managerName.equals(attrValues[0].toString())) {
                                for (int i = 1; i < attrValues.length; i++) {
                                    result[i - 1] = attrValues[i].toString();
                                    propValues[i - 1] = ResPropertyValue.createPropValue(attrValues[i].toString(), propMetas[i - 1]);
                                }
                            }
                        }
                    }
                }
            }

        } catch (Exception e) {
            logger.error("failed to collect by WorkManagerCollector", e);
            throw new CollectorException(e);
        } finally {
            JmxUtil.closeConnector(connector);
        }
        if (perComRequest.get(key) != null) {
            String temp = String.valueOf(perComRequest.get(key));
            String[] valueTime = temp.split(":");
            result[2] = String.valueOf((Long.parseLong(valueTime[0]) - Long.parseLong(result[1])) * 1000 * 60 / (time - Long.parseLong(valueTime[1])));

            propValues[2] = ResPropertyValue.createPropValue(String.valueOf((Long.parseLong(valueTime[0]) - Long.parseLong(attrValues[1].toString())) * 1000 * 60 / (time - Long.parseLong(valueTime[1]))), propMetas[2]);
            if (Long.parseLong(result[2]) < 0) {
                result[2] = "0";
            }
        }
        perComRequest.remove(key);
        perComRequest.put(key, attrValues[1] + ":" + String.valueOf(time));
        propertyValueX.setValues(propValues);
        values.add(propertyValueX);
        return values;
    }

    @Override
    public String[] getParamMeta() {
        return new String[] { "ServerName", "AppName", "ManagerName", "port" };
    }

    @Override
    public String[] getPropMeta() {
        //return new String[] { "PendingRequests", "CompletedRequests", "rollbackms" };
        return new String[] { "$1", "$2", "$3" };
    }

}
